<?php

/**
 *    售货员控制器，其扮演实际交易中柜台售货员的角色，你可以这么理解她：你告诉我（售货员）要买什么东西，我会询问你你要的收货地址是什么之类的问题
 ＊        并根据你的回答来生成一张单子，这张单子就是“订单”
 *
 *    @author    Garbin
 *    @param    none
 *    @return    void
 */
class OrderApp extends ShoppingbaseApp
{
	/**
     *    填写收货人信息，选择配送，支付方式。
     *
     *    @author    Garbin
     *    @param    none
     *    @return    void
     */
	function index()
	{

		/* 根据商品类型获取对应的订单类型 */
		$goods_type =& gt('material');//实体商品
		$order_type =& ot('normal');  //普通订单，非团购

		$user_id = $this->visitor->get('user_id');

		$address_list  = array_values($order_type->_get_my_address($user_id));
		$default_address = $address_list[0];//获取第一个地址
		$this->assign('my_address', $address_list);

		//切换了新地址
		$address_id = intval($_GET['address_id']);
		if ($address_id)
		{
			$default_address = $order_type->_get_address_by_id($address_id);
		}


		$this->assign('default_address', $default_address);
		$this->assign('address_id', $address_id);


		/* 获取所有购物车 */
		$trans_list = $this->_get_trans($default_address['region_id']);//按店铺分组的订单列表
		//echo "<pre>";
		//print_r($trans_list);die();
		if (empty($trans_list))
		{
			/* 购物车是空的 */
			$this->show_warning('goods_empty', "去购物车", "index.php?app=cart", "查看我的订单", "index.php?app=buyer_order", "返回上一页");
			return;
		}

		foreach ($trans_list as $store_id => $order)
		{
			$data['quantity'] += $order['quantity'];
			$data['amount']   += $order['amount'];
			$data['kinds']    += $order['kinds'];
			$data['shipping_fee']    += $order['shipping_fee'];
			$data['total']    += $order['total'];
		}

		/* 显示订单表单 */
		$this->_curlocal(
		LANG::get('create_order')
		);
		$this->_config_seo('title', Lang::get('create_order') . ' - ' . Conf::get('site_title'));

		//显示位置
		$shopcar_step = 'shopcar02';
		$this->assign('shopcar_step', $shopcar_step);

		$regions = $order_type->_get_regions();
		$this->assign('regions', $regions);//一级地区

		$this->assign('trans_list', $trans_list);//订单列表
		$this->assign('order_total',$data);//订单总信息
		$this->display('order.form.html');

	}

	/**
     *    填写收货人信息，选择配送，支付方式。
     *
     *    @author    Garbin
     *    @param     none
     *    @return    void
     */
	function make_order()
	{


		/* 根据商品类型获取对应的订单类型 */
		$goods_type =& gt('material');//实体商品
		$order_type =& ot('normal');  //普通订单，非团购

		$user_id = $this->visitor->get('user_id');


		$address_id = intval($_POST['address_options']);
		if (empty($address_id))
		{
			/* 地址是空的 */
			$this->show_warning('请选择收货地址');
			return;
		}
		$default_address = $order_type->_get_address_by_id($address_id);

		if (empty($default_address))
		{
			/* 地址是空的 */
			$this->show_warning('请选择收货地址');
			return;
		}

		/* 获取所有购物车 */
		$trans_list = $this->_get_trans($default_address['region_id']);//按店铺分组的订单列表
		//echo "<pre>";
		//print_r($trans_list);die();
		if (empty($trans_list))
		{
			/* 购物车是空的 */
			$this->show_warning('goods_empty');
			return;
		}

		foreach ($trans_list as $store_id => $order)
		{
			/*$data['quantity'] += $order['quantity'];
			$data['amount']   += $order['amount'];
			$data['kinds']    += $order['kinds'];
			$data['shipping_fee']    += $order['shipping_fee'];
			$data['total']    += $order['total'];*/
			foreach ($order['goods'] as $key =>$goods)
			{
				$goods_info[] = $goods;
			}
		}
		//print_r($goods_info);die();
		/*  检查库存 */
		$goods_beyond = $this->_check_beyond_stock($goods_info);
		unset($goods_info);
		if ($goods_beyond)
		{
			$str_tmp = '';
			foreach ($goods_beyond as $goods)
			{
				$str_tmp .= '<br /><br />' . $goods['goods_name'] . '&nbsp;&nbsp;' . $goods['specification'] . '&nbsp;&nbsp;' . Lang::get('stock') . ':' . $goods['stock'];
			}
			$this->show_warning(sprintf(Lang::get('quantity_beyond_stock'), $str_tmp),'返回购物车','index.php?app=cart');
			return;
		}

		//一个店铺一个订单号
		foreach ($trans_list as $store_id => $order)
		{
			/* 将这些信息传递给订单类型处理类生成订单(你根据我提供的信息生成一张订单) */
			$order_info = array();
			$order_info['amount']       = $order['amount'];       //商品总价
			$order_info['type']         = 'material';       //商品类型
			$order_info['shipping_fee'] = $order['shipping_fee']; //商品运费
			$order_info['total']        = $order['total'];       //订单总额
			$order_info['store_id']     = $store_id;
			$order_info['store_name']   = $order['store_name'];
			$order_info['postscript']   = html_script($_POST['message'.$store_id]);   //留言
			//发票信息
			$is_inv = intval($_POST['is_invoice'.$store_id]);//是否开发票
			if($is_inv==1)
			{
				$inv_content =  intval($_POST['invoice_type'.$store_id])==1?'个人':html_script($_POST['inv_content'.$store_id]);
			}
			$order_info['inv_content']   = $inv_content;   //发票抬头
			//插入数据库订单信息
			$order_id = $order_type->submit_order(array(
			'goods_info'    =>  $order['goods'],      //商品信息
			'order_info'    =>  $order_info,          //用户填写的订单信息
			'address_info'  =>  $default_address,   //用户填写的订单信息
			));
			if (!$order_id)
			{
				//可以抛出异常处理
				//$this->show_warning($order_type->get_error());
				//return;
			}
			else
			{
				$order_arr[$store_id] = $order_id;//为异步调用
				$this->_clear_goods($store_id);//清空购物车
				/* 减去商品库存 */
				$model_order =& m('order');
				$model_order->change_stock('-', $order_id);

			}
		}

		unset($order_info);
		unset($order);

		/*  检查是否添加收货人地址  */
		/*	if (isset($_POST['save_address']) && (intval(trim($_POST['save_address'])) == 1))
		{
		$data = array(
		'user_id'       => $this->visitor->get('user_id'),
		'consignee'     => trim($_POST['consignee']),
		'region_id'     => $_POST['region_id'],
		'region_name'   => $_POST['region_name'],
		'address'       => trim($_POST['address']),
		'zipcode'       => trim($_POST['zipcode']),
		'phone_tel'     => trim($_POST['phone_tel']),
		'phone_mob'     => trim($_POST['phone_mob']),
		);
		$model_address =& m('address');
		$model_address->add($data);
		}*/

		//优化时候以下可以异步处理
		/* 发送邮件 */

		foreach ($trans_list as $store_id => $order)
		{

			if(array_key_exists($store_id,$order_arr))//成功的订单才处理
			{

				/* 获取订单信息 */
				//$model_order =& m('order');
				$order_info = $model_order->get($order_arr[$store_id]);

				/* 发送事件 */
				/*$feed_images = array();
				foreach ($order['goods'] as $_gi)
				{
				$feed_images[] = array(
				'url'   => SITE_URL . '/' . $_gi['goods_image'],
				'link'  => SITE_URL . '/' . url('app=goods&id=' . $_gi['goods_id']),
				);
				}
				$this->send_feed('order_created', array(
				'user_id'   => $this->visitor->get('user_id'),
				'user_name' => addslashes($this->visitor->get('user_name')),
				'seller_id' => $order_info['seller_id'],
				'seller_name' => $order_info['seller_name'],
				'store_url' => SITE_URL . '/' . url('app=store&id=' . $order_info['seller_id']),
				'images'    => $feed_images,
				));*/

				//$buyer_address = $this->visitor->get('email');
				// echo $user_id.'aa'.$this->visitor->get('user_id');die();
				$model_usersafety = & m('usersafety');
				$buyer_info       = $model_usersafety->get("user_id='{$user_id}'");
				$buyer_address    = $buyer_info['binding_email'];//买家绑定的邮件

				if($buyer_address)
				{
					/* 发送给买家下单通知 */
					$buyer_mail = get_mail('tobuyer_new_order_notify', array('order' => $order_info));
					$this->_mailto($buyer_address, addslashes($buyer_mail['subject']), addslashes($buyer_mail['message']));
				}

				$seller_info      = $model_usersafety->get("user_id='{$store_id}'");
				$seller_address   = $seller_info['binding_email'];//卖家绑定的邮件

				if($seller_address)
				{
					/* 发送给卖家新订单通知 */
					$seller_mail = get_mail('toseller_new_order_notify', array('order' => $order_info));
					$this->_mailto($seller_address, addslashes($seller_mail['subject']), addslashes($seller_mail['message']));
				}

				/* 更新下单次数 */
				$model_goodsstatistics =& m('goodsstatistics');
				$goods_ids = array();
				foreach ($order['goods'] as $goods)
				{
					$goods_ids[] = $goods['goods_id'];
				}
				$model_goodsstatistics->edit($goods_ids, 'orders=orders+1');
			}
		}


		unset($order_info);
		unset($order);
		unset($trans_list);
		/* 到收银台付款 */
		$order_ids = implode(',',$order_arr);
		header('Location:index.php?app=cashier&order_id=' . $order_ids);
	}


	//确认订单列表，包运费
	function _get_trans($region_id = 0)
	{
		$carts = array();

		/* 只有是自己购物车的项目才能购买 */
		$where_user_id = $this->visitor->get('user_id') ? " AND cart.user_id=" . $this->visitor->get('user_id') : '';
		$cart_model =& m('cart');
		$cart_items = $cart_model->find(array(
		'conditions'    => 'session_id = \'' . SESS_ID . "'" . $where_user_id .' AND cart.status=1',
		'fields'        => 'this.*,store.store_name,store.im_qq,store.im_ww,goodsspec.stock',
		'join'          => 'belongs_to_store,belongs_to_goodsspec',
		'order'         => 'goods_id DESC, spec_id DESC',
		));
		if (empty($cart_items))
		{
			return $carts;
		}

		//计算运费模板
		foreach ($cart_items as $item)
		{
			$shipping_id_count[$item['shipping_id']]++;
			$shipping_id = $item['shipping_id'];
			if(!isset($shippings[$shipping_id]))
			{
				$shippings[$shipping_id]['rowspan'] = 0;
				$shippings[$shipping_id]['shipping_quantity'] = 0;//计算运费的产品数量
				$shippings[$shipping_id]['shipping_weight'] = 0;//计算运费的产品重量
				$shippings[$shipping_id]['shipping_amount']  = 0;//计算运费的产品金额
				$shippings[$shipping_id]['shipping_fee'] = 0;//运费
				$shippings[$shipping_id]['shipping_desc'] = '';//运费详情
				$shippings[$shipping_id]['shipping_name'] = '';//模板名称
				$shippings[$shipping_id]['unit'] = 0;//货品总量
			}

			$shippings[$shipping_id][$item['goods_id']]['shipping_quantity'] += $item['quantity'];
			$shippings[$shipping_id][$item['goods_id']]['shipping_weight']   = $item['goods_weight'];

			$shippings[$shipping_id]['shipping_quantity'] += $item['quantity'];
			$shipping_amount   = $item['price'] * $item['quantity'];
			$shippings[$shipping_id]['shipping_amount']   += $shipping_amount;
			$shippings[$shipping_id]['shipping_type'] = $item['shipping_type'];
		}

		foreach ($cart_items as $item)
		{
			$shipping_id = $item['shipping_id'];
			$shippings[$shipping_id]['rowspan']++;   //前台展示用

			if($shipping_id_count[$shipping_id] == $shippings[$shipping_id]['rowspan'])
			{
				foreach($shippings[$shipping_id] as $goods)
				{
					if(is_array($goods))
					{
						$shippings[$shipping_id]['shipping_weight'] += $goods['shipping_quantity'] * $goods['shipping_weight'];
					}
				}

				$shipping_data  = $this->_get_shipping_fee($shippings[$shipping_id]['shipping_type'],$shipping_id,$shippings[$shipping_id]['shipping_weight'],$shippings[$shipping_id]['shipping_amount'],$shippings[$shipping_id]['shipping_quantity'],$region_id);
				$shippings[$shipping_id]['shipping_fee']  = $shipping_data['shipping_fee'];
				$shippings[$shipping_id]['shipping_desc']  = $shipping_data['shipping_desc'];
				$shippings[$shipping_id]['shipping_name']  = $shipping_data['shipping_name'];
				$shippings[$shipping_id]['unit']  = $shipping_data['unit'];
			}
		}

		$kinds = array();
		$shipping_ids = array();
		foreach ($cart_items as $item)
		{
			$shipping_id = $item['shipping_id'];

			//将运费模板放到购物车中
			if(!in_array($shipping_id, $shipping_ids))
			{
				$cart_items[$item['rec_id']]['rowspan'] = $shippings[$shipping_id]['rowspan'];
				$cart_items[$item['rec_id']]['shipping_fee'] = $shippings[$shipping_id]['shipping_fee'];
				$cart_items[$item['rec_id']]['shipping_desc'] = $shippings[$shipping_id]['shipping_desc'];
				$cart_items[$item['rec_id']]['shipping_name'] = $shippings[$shipping_id]['shipping_name'];
				$cart_items[$item['rec_id']]['unit'] = $shippings[$shipping_id]['unit'];

				$carts[$item['store_id']]['shipping_fee'] += $shippings[$shipping_id]['shipping_fee'];
			}
			$shipping_ids[] = $shipping_id;
			$item = $cart_items[$item['rec_id']];
			//end 计算运费模板

			/* 小计 */
			$item['subtotal']   = $item['price'] * $item['quantity'];
			$kinds[$item['store_id']][$item['goods_id']] = 1;

			/* 以店铺ID为索引 */
			empty($item['goods_image']) && $item['goods_image'] = Conf::get('default_goods_image');
			$carts[$item['store_id']]['store_name'] = $item['store_name'];
			$carts[$item['store_id']]['amount']     += $item['subtotal'];   //各店铺的总金额（不含运费）
			$carts[$item['store_id']]['quantity']   += $item['quantity'];   //各店铺的总数量
			$carts[$item['store_id']]['goods'][]    = $item;
		}

		foreach ($carts as $_store_id => $cart)
		{
			$carts[$_store_id]['kinds'] =   count(array_keys($kinds[$_store_id]));  //各店铺的商品种类数
			$carts[$_store_id]['total']     += $cart['amount'] + $cart['shipping_fee'];//各店铺的总金额（含运费）
		}

		return $carts;
	}

	/**
 * 计算运费
 * @param   string  $shipping_type      送货方式，1为快递，2为货运
 * @param   string  $shipping_id        配送方式ID
 * @param   float   $goods_weight       商品重量
 * @param   float   $goods_amount       商品金额
 * @param   float   $goods_number       商品数量
 * @param   float   $region_id          地区ID
 * @return  float   运费
 */
	function _get_shipping_fee($shipping_type,$shipping_id, $goods_weight, $goods_amount, $goods_number,$region_id)
	{
		$shipping_type  = intval($shipping_type);//送货方式
		$shipping_id    = intval($shipping_id);
		$goods_number   = intval($goods_number);
		$region_id      = intval($region_id);
		if($shipping_type==2)//货运
		{

			$shipping['shipping_fee']  = 0;//运费
			$shipping['shipping_desc'] = $shipping_id==0?'卖家承担运费':'运费到付';//运费详情

			return $shipping;
		}

		else //快递
		{

			if(empty($shipping_id))
			{

				$shipping['shipping_fee']  = 0;//运费
				$shipping['shipping_desc'] = '卖家承担运费';//运费详情

				return $shipping;
			}
			$shipping_mod = &m('shipping');
			$shipping = $shipping_mod->shipping_fee($shipping_id, $goods_weight, $goods_amount, $goods_number,$region_id);
			return $shipping;
		}

	}


	/**
     *    下单完成后清理商品
     *
     *    @author    Garbin
     *    @return    void
     */
	function _clear_goods($store_id)
	{

		/* 订单下完后清空指定购物车 */
		$store_id = intval($store_id);
		if (!$store_id)
		{
			return false;
		}
		$model_cart =& m('cart');
		$model_cart->drop("session_id='" . SESS_ID . "'AND store_id = {$store_id} AND status=1");


	}

	function _check_beyond_stock($goods_items)
	{
		$goods_beyond_stock = array();
		foreach ($goods_items as $key => $goods)
		{
			if ($goods['quantity'] > $goods['stock'])
			{
				$goods_beyond_stock[$goods['spec_id']] = $goods;
			}
		}
		return $goods_beyond_stock;
	}


	//添加收货地址
	function ajaxAddAddress()
	{

		if (!$_POST['consignee'] || !$_POST['region_name'] || !$_POST['address'] || (!$_POST['phone_mob'] && !$_POST['phone_code']))
		{
			$result['success'] = 0;
			echo ecm_json_encode($result);
			exit;
		}

		if ((!is_mobile($_POST['phone_mob']) && $_POST['phone_mob'])  || (!is_zipcode($_POST['zipcode']) && $_POST['zipcode']))
		{

			$result['success'] = 0;
			echo ecm_json_encode($result);
			exit;
		}

		$data = array(
		'user_id'       => $this->visitor->get('user_id'),
		'consignee'     => html_script(trim($_POST['consignee'])),
		'region_id'     => (int)$_POST['region_id'],
		'region_name'   => html_script(trim($_POST['region_name'])),
		'address'       => html_script(trim($_POST['address'])),
		'zipcode'       => html_script(trim($_POST['zipcode'])),
		'phone_mob'     => html_script(trim($_POST['phone_mob'])),
		'is_deafult'     => isset($_POST['defaulti']) ? (int)$_POST['defaulti'] : 0 ,

		);
		if($_POST['phone_code'] && $_POST['phone_section'])
		{
			if($_POST['phone_ext'])
			{
				$data['phone_tel'] = trim($_POST['phone_section']).'-'.trim($_POST['phone_code']).'-'.trim($_POST['phone_ext']);
			}
			else
			{
				$data['phone_tel'] = trim($_POST['phone_section']).'-'.trim($_POST['phone_code']);
			}
			if (!is_tel($data['phone_tel']))
			{
				$result['success'] = 0;
				echo ecm_json_encode($result);
				exit;
			}
		}
		else
		{
			$data['phone_tel'] = '';
		}
		$model_address =& m('address');
		$sql = "SELECT COUNT(*) FROM {$model_address->table} WHERE `user_id` = " . $this->visitor->get('user_id');
		if((int)$model_address->getOne($sql)>=10)
		{
			$result['success'] = 0;
			echo ecm_json_encode($result);
			exit;
		}

		if($data['is_deafult'] == 1)//如果添加的设置为默认
		{
			$model_address->edit("user_id=" . $this->visitor->get('user_id') ." AND is_deafult=1 ", array('is_deafult'=>0));//之前的默认设置为非默认
		}

		$address_id = $model_address->add($data);

		if($address_id)
		{
			$result['success'] = true;
			$result['address_id'] = $address_id;
			$result['region_name'] = $data['region_name'];
			$result['address'] = $data['address'];
			$result['consignee'] = $data['consignee'];
			$result['phone_mob'] = $data['phone_mob'];
			$result['phone_tel'] = $data['phone_tel'];
			$result['is_deafult'] = $data['is_deafult'];

			echo ecm_json_encode($result);
			exit;
		}
	}


}
?>
